
from lxml import etree
from util.selenium.webdriver.common.by import By
from util.selenium.webdriver.support.wait import WebDriverWait
from util.selenium.webdriver.support import expected_conditions as EC

from spider_data.spiderBaseMethod import bm
from util.g import g


def parseMainCase(driver=None):
    try:
        bm.detail_switch_iframe(driver=driver)
        main_case_loc = (By.LINK_TEXT, '主要情况表')

        # # # 点击 主要情况表按钮。

        WebDriverWait(driver=driver, timeout=10, poll_frequency=0.5).until(
            EC.presence_of_all_elements_located(main_case_loc))

        driver.find_element(*main_case_loc).click()
        # # # 等待标题加载出来
        WebDriverWait(driver=driver, timeout=10, poll_frequency=0.5).until(
            EC.presence_of_all_elements_located(g.title_loc))

        # # # # #  解析主要情况表的数据，
        main_case_text = driver.page_source

        tree = etree.HTML(main_case_text)
        # print(main_case_text)
        # tree = bm.get_first(tree.xpath('//div[contains(@class, "box-body")]'))
        # /html/body/div[1]/div[4]/div[2] /html/body/div[1]/div[4]/div[2]
        # # 技术领域

        #  需要在数据库中查找出分别对应的领域的id。
        domain1 = bm.get_first(li=tree.xpath("//div[@id='uniform-onemain']/span/text()"))
        domain2 = bm.get_first(li=tree.xpath("//div[@id='uniform-scdmain']/span/text()"))
        domain3 = bm.get_first(li=tree.xpath("//div[@id='uniform-thdmain']/span/text()"))
        domain = ",".join([domain1, domain2, domain3])
        # print(domain)

        # # 知识产权数量

        i_num = bm.get_int(tree.xpath("//input[@id='getNumber1']/@value"))

        ii_num = bm.get_int(tree.xpath("//input[@id='getNumber2']/@value"))
        # print(i_num, ii_num)
        # 人力资源情况表
        stff_num = bm.get_int(tree.xpath("//input[@id='zgzs']/@value"))
        tech_num = bm.get_int(tree.xpath("//input[@id='humanScience']/@value"))
        # print(stff_num, tech_num)
        # # 企业经营情况
        mat_ai = bm.get_float(tree.xpath("//input[@id='enterpriseIncome']/@value"))
        techout_ai = bm.get_float(tree.xpath("//input[@id='highIncome']/@value"))
        spend_total = bm.get_float(tree.xpath("//input[@id='kffyze']/@value"))
        inchina_spend = bm.get_float(tree.xpath("//input[@id='chinaCost']/@value"))
        basic_spend = bm.get_float(tree.xpath("//input[@id='basicsCost']/@value"))

        # print(mat_ai, techout_ai, spend_total, inchina_spend, basic_spend)

        is_events_name = bm.join_and_repalce(tree.xpath('//input[@checked="checked"]/@value'))
        # # # 0 否 1 是
        is_events = 0 if is_events_name == '否' or is_events_name == "0" else 1
        # # #  主要情况表中的数据。  调用 db_operate 中的 SaveData 模块将数据存入数据库
        WriteMaincaseForm = {'tech_fieldname': domain, 'i_num': i_num, 'ii_num': ii_num, 'stff_num': stff_num,
                             'tech_num': tech_num, 'mat_ai': mat_ai, 'techout_ai': techout_ai, 'spend_total': spend_total,
                             'inchina_spend': inchina_spend, 'basic_spend': basic_spend, 'is_events': is_events}

        # g.co_id = 2019
        WriteOptcond = list()
        for i in range(3):
            optcond = {'category': '', 'net_assets': '', 'net_revenues': '', 'net_income': ''}
            num = i + 1
            row = bm.get_first(tree.xpath("//div[contains(@class, 'input-box3')]/div[{}]".format(num)))
            year = bm.get_ids(id_str=row.xpath("./label/text()"))
            optcond["category"] = g.year - year
            net_assets = tree.xpath("//input[@id='netAsset{}']/@value".format(num))
            optcond["net_assets"] = bm.get_float_str(s=net_assets)
            net_revenues = tree.xpath("//input[@id='salesRevenue{}'/@value".format(num))
            optcond["net_revenues"] = bm.get_float_str(s=net_revenues)
            net_income = tree.xpath("//input[@id='totalProfit{}/@value".format(num))
            optcond["net_income"] = bm.get_float_str(s=net_income)
            WriteOptcond.append(optcond)

        # driver.switch_to.default_content()
        return {"key": "WriteMaincaseForm", "value": {"WriteMaincaseForm": WriteMaincaseForm, "WriteOptcond": WriteOptcond}}
    except Exception as err:
        msg = "error: {} file: {} lines: {}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                    err.__traceback__.tb_lineno)
        g.logger.error(msg)
        raise Exception(msg)
